package com.example.kingdee.jstSync.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONArray;
import com.example.kingdee.KingdeeCreate.dto.CreateInDto;
import com.example.kingdee.KingdeeCreate.impl.CreateSalBillImpl;
import com.example.kingdee.block.JuShuiTanBlock;
import com.example.kingdee.common.StringUtils;
import com.example.kingdee.dto.PurchaseSyncDto;
import com.example.kingdee.dto.SyncDto;
import com.example.kingdee.entity.JstRefund;
import com.example.kingdee.entity.JstSalOrder;
import com.example.kingdee.entity.SyncLog;
import com.example.kingdee.jstSync.JstSyncAbstract;
import com.example.kingdee.jstSync.entity.JstResult;
import com.example.kingdee.kingdeeBridge.common.RequestResult;
import com.example.kingdee.mapper.TBxStMapper;
import com.example.kingdee.sqlTool.SqlTool;
import com.example.kingdee.sqlTool.sqltoolEnum.FormIdEnum;
import com.example.kingdee.util.JuShuiTanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 聚水潭采购订单同步实现类
 */
@Service
public class JstReFundSyncImpl extends JstSyncAbstract {

    @Autowired
    private JuShuiTanBlock juShuiTanBlock;
    @Autowired
    private CreateSalBillImpl createSalBill;

    @Autowired
    private TBxStMapper tBxStMapper;

    @Override
    public int getOrderInfoPage(SyncDto syncDto, PurchaseSyncDto purchaseSyncDtoPage) {
        return JuShuiTanUtil.getRefundInfoPage(purchaseSyncDtoPage, FormIdEnum.refundQuery, juShuiTanBlock.getAccessToken());
    }

    @Override
    public JstResult selectJstResult(SyncDto syncDto,  PurchaseSyncDto purchaseSyncDto) {
        JstResult jstResult = new JstResult();
        //制定查询状态
        purchaseSyncDto.setJstFormId(FormIdEnum.refundQuery.name());
        purchaseSyncDto.setStatusList(syncDto.getStatus());
        String jstInfoStr = juShuiTanBlock.getJstReFundInfo(purchaseSyncDto);
        //格式化单据
        List<JstRefund> jstRefundList = JSONArray.parseArray(jstInfoStr, JstRefund.class);
        jstResult.setJstReFundOrderList(jstRefundList);
        return jstResult;
    }

    @Override
    public void kingdeeSync(SyncDto syncDto, JstResult jstResult) {
        List<JstRefund> jstReFundOrderList = jstResult.getJstReFundOrderList();
        for (JstRefund jstRefund : jstReFundOrderList) {
            try {
                // 处理单个订单
                processSingleOrder(jstRefund);
            } catch (Exception e) {
                // 记录未知异常日志
                createErrorLog(jstRefund, "处理过程中发生未知异常: " + e.getMessage());
            }
        }

    }

    /**
     * 处理单个订单
     */
    private void processSingleOrder(JstRefund jstRefund) {
        // 初始化同步日志
        SyncLog syncLog = initSyncLog(jstRefund);

        // 只处理仅退款的售后单
        if (!jstRefund.getType().equals("仅退款")) {
            return;
        }

        // 检查是否已处理过
        if (isAlreadyProcessed(jstRefund)) {
            return;
        }

        // 关闭对应销售订单
        buildAndSyncOrder(jstRefund, syncLog);
    }

    /**
     * 构建订单明细并同步
     */
    private void buildAndSyncOrder(JstRefund jstRefund, SyncLog syncLog) {
        //查询云星空是否存在相应销售订单
        List<Map<String, Object>> salOrderList = tBxStMapper.selectSalOrder(String.valueOf(jstRefund.getOId()));
        if (salOrderList.isEmpty()) {
            syncLog.setSyncResult("同步失败");
            syncLog.setSyncErrorMsg("售后对应的订单未同步到金蝶中");
            tBxStMapper.insertSyncLog(syncLog);
        }else {
            for (Map<String, Object> salOrder : salOrderList) {
                if (String.valueOf(salOrder.get("billStatus")).equals("A")){
                    //关闭对应销售订单
                    try {
                        CreateInDto createInDto = new CreateInDto();
                        createInDto.setReserved1(salOrder.get("billId")); // 销售订单id
                        createSalBill.closeKingdeeSal(createInDto);
                        syncLog.setSyncResult("同步成功");
                        syncLog.setKingdeeBillno(String.valueOf(salOrder.get("billNo")));
                        syncLog.setSyncErrorMsg("无");
                    } catch (Exception e) {
                        syncLog.setSyncResult("同步失败");
                        syncLog.setSyncErrorMsg(e.getMessage());
                    }
                    tBxStMapper.insertSyncLog(syncLog);
                }else {
                    syncLog.setSyncResult("同步失败");
                    syncLog.setSyncErrorMsg("售后对应的订单已关闭");
                    tBxStMapper.insertSyncLog(syncLog);
                }

            }
        }

    }

    /**
     * 检查是否已处理过
     */
    private boolean isAlreadyProcessed(JstRefund jstRefund) {
        int havaErrorLog = tBxStMapper.isHavaErrorLog(jstRefund.getAsId());
        int havaLog = tBxStMapper.isHavaLog(jstRefund.getAsId());
        return havaErrorLog > 0 || havaLog > 0;
    }

    /**
     * 初始化同步日志
     */
    private SyncLog initSyncLog(JstRefund jstRefund) {
        SyncLog syncLog = new SyncLog();
        syncLog.setSyncType("售后订单处理");
        syncLog.setSyncTime(SqlTool.getNowForString());
        syncLog.setSyncUser("接口自动同步");
        syncLog.setIsDispose("未处理");
        syncLog.setSrcBill("聚水潭售后订单");
        syncLog.setTarBill("云星空销售订单");
        syncLog.setJstBillno(String.valueOf(jstRefund.getAsId()));
        syncLog.setObjectId(String.valueOf(jstRefund.getAsId()));
        return syncLog;
    }

    /**
     * 创建错误日志
     */
    private void createErrorLog(JstRefund jstRefund, String errorMsg) {
        SyncLog syncLog = initSyncLog(jstRefund);
        syncLog.setSyncResult("同步失败");
        syncLog.setSyncErrorMsg(errorMsg);
        tBxStMapper.insertSyncLog(syncLog);
    }



    @Override
    protected void insertSyncLog(SyncDto syncDto, SyncLog syncLog, boolean isSucceed) {
        syncLog.setSyncType("采购订单同步");
        syncLog.setSrcBill("聚水潭采购单");
        syncLog.setTarBill("金蝶销售单");
        syncLog.setSyncTime(SqlTool.getNowForString());
        syncLog.setSyncUser(syncDto.getUserName() == null ? "系统自动同步" : syncDto.getUserName());
        if (isSucceed){
            syncLog.setSyncResult("同步成功");
            syncLog.setSyncErrorMsg("无");
        }else {
            syncLog.setIsDispose("未处理");
            syncLog.setSyncResult("同步失败");
        }
        tBxStMapper.insertSyncLog(syncLog);
    }
}
